package com.java.Servlet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// initParams用于配置初始化参数
@WebServlet(value = "/servlet-context", initParams = {@WebInitParam(name = "param", value = "value")})
public class ServletContextAPI extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取上下文对象
        ServletContext context = this.getServletContext();

        // setAttribute：设置键值对
        context.setAttribute("user", "syx");
        context.setAttribute("age", 19);

        // getInitParameter：获取初始化参数，上下文只能获取到全局初始化参数
        System.out.println(context.getInitParameter("param")); // null
        System.out.println(this.getInitParameter("param")); // value

        // getRequestDispatcher：请求转发
        RequestDispatcher dispatcher = context.getRequestDispatcher("/dispatcher");
        dispatcher.forward(req, resp);
    }
}
